package com.vic.framework.helper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import com.vic.framework.bean.FormParam;
import com.vic.framework.bean.Param;
import com.vic.framework.utils.CoderUtil;
import com.vic.framework.utils.StreamUtil;

/**
 * 请求助手类
 * @author VIC
 *
 */
public final class RequestHelper {
	
	/**
	 * 创建请求对象
	 */
	public static Param createParam(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList = new ArrayList<FormParam>();
		formParamList.addAll(parseParamterNames(request));
		formParamList.addAll(parseInputStream(request));
		return new Param(formParamList);
		
	}
	
	
	private static List<FormParam> parseParamterNames(HttpServletRequest request) {
		List<FormParam> formParamList = new ArrayList<FormParam>();
		Enumeration<String> paramNames = request.getParameterNames();
		while( paramNames.hasMoreElements()) {
			String fieldName = paramNames.nextElement();
			String[] fieldValues = request.getParameterValues(fieldName);
			if(ArrayUtils.isNotEmpty(fieldValues)) {
				Object fieldValue;
				if(fieldValues.length == 1) {
					fieldValue = fieldValues[0];
				}else {
					StringBuilder sb = new StringBuilder();
					for(int i = 0; i < fieldValues.length; i++) {
						sb.append(fieldValues[i]);
						if(i != fieldValues.length -1) {
							sb.append(",");
						}
					}
					fieldValue = sb.toString();
				}
				formParamList.add(new FormParam(fieldName, fieldValue));
			}
		}
		return formParamList;
	}
	
	
	private static List<FormParam> parseInputStream(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList = new ArrayList<FormParam>();
		String body = CoderUtil.decoderURL(StreamUtil.getString(request.getInputStream()));
		
		if(StringUtils.isNotEmpty(body)) {
			String[] kvs = StringUtils.split(body, "&");
			if(ArrayUtils.isNotEmpty(kvs)) {
				for(String kv : kvs) {
					String[] array = StringUtils.split(kv, "=");
					if(ArrayUtils.isNotEmpty(array) && array.length ==2) {
						String fieldName = array[0];
						String fieldValue = array[1];
						formParamList.add(new FormParam(fieldName, fieldValue));
					}
				}
			}
		}
		return formParamList;
	}

}
